<script setup>
import {useRouter, useRoute} from "vue-router";
import {reactive, ref, onMounted, computed, onBeforeMount} from "vue";
import {catMove, catFall} from '@/util/animate/animate_1.js'
import {HTTP} from "@/api/HTTP.js";
import {ElMessage} from "element-plus";
// 加入动画
catMove('.cat')// 加入动画

const router = useRouter()
// 全部选中状态
const AllChecked = ref(false)

// 控制结算框显示和隐藏
const dialogFormVisible = ref(false)

// 商品总价
const totalPriceList = ref([])
// 购物车数据
const cart_data = ref([])
// 获取购物车数据
onMounted(async () => {
  try {
    catFall('.cat'); // 假设这是一个动画函数

    const response = await HTTP.get('/cart');
    console.log(response);

    if (Object.keys(response.data).length === 0) {
      ElMessage({
        message: '购物车空空如也~',
        type: 'warning',
      });
      return;
    }
    cart_data.value.push(...response.data.productInfoVos);
  } catch (error) {
    console.error('Error fetching cart data:', error);
    ElMessage({
      type: 'error',
      message: '获取购物车数据失败，请检查网络或稍后再试。'
    });
  }
})
// 返回上一页
const handleBack = () => {
  router.go(-1)
}
// 是否选中
const handleCheckOut = (event) => {
  if (totalPriceList.value.length === 0) {
    AllChecked.value = false
    return
  }
// 设置 AllChecked.value
  AllChecked.value = totalPriceList.value.length === cart_data.value.length
}

// 全选功能
const handleCheckAll = () => {
  totalPriceList.value = AllChecked.value ? cart_data.value : []
}

// 删除某一个购物车数据
const handleDelete = async (id) => {
  console.log(id)
  try {
    // 发送删除请求
    const response = await HTTP.delete(`/cart?cart_id=${id}`);

    if (response.code === 10200) {
      ElMessage({
        message: '商品删除成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '商品删除失败',
        type: 'error',
      });
    }
// 更新 cart_data.value
    cart_data.value = cart_data.value.map(item => ({
      ...item, // 复制原始对象
      type: item.type.filter(typeItem => typeItem.cart_id !== id) // 过滤 type 数组
    }));

    totalPriceList.value = totalPriceList.value.map(item => ({
      ...item, // 复制原始对象
      type: item.type.filter(typeItem => typeItem.cart_id !== id) // 过滤 type 数组
    }));

// 清理空的 type 数组
    cart_data.value = cart_data.value.filter(item => {
      return item.type.length !== 0;

    });
    totalPriceList.value = totalPriceList.value.filter(item => {
      return item.type.length !== 0;

    });
  } catch (error) {
    console.error('商品删除失败:', error);
  }
};

// 结算
const TotalPrice = computed(() => {
  return totalPriceList.value.reduce((total, item) => total + Math.abs(item.price), 0)
})

// 删除全部
const handleDeleteAll = async () => {
  try {
    let cart = []
    totalPriceList.value.forEach(item => {
      item.type.forEach(typeItem => {
        cart.push(typeItem.cart_id)
      })
    })
    // 获取所有要删除的商品 ID
    const idsToDelete = cart.map(item => item);

    // 批量删除商品
    await Promise.all(idsToDelete.map(id =>
        HTTP.delete(`/cart?cart_id=${id}`)
            .then(res => {
              if (res.code === 10600) {
                ElMessage({
                  message: '商品不在购物车',
                  type: 'warning',
                });
              } else if (res.code === 10200) {
                console.log(res);
                ElMessage({
                  message: '商品删除成功',
                  type: 'success',
                });
              }
            })
    ));


    // 更新 cart_data
    cart_data.value = cart_data.value.map(item => ({
      ...item, // 复制原始对象
      type: item.type.filter(typeItem => !idsToDelete.includes(typeItem.cart_id)) // 过滤 type 数组
    }));
    totalPriceList.value = totalPriceList.value.map(item => ({
      ...item, // 复制原始对象
      type: item.type.filter(typeItem => !idsToDelete.includes(typeItem.cart_id)) // 过滤 type 数组
    }));

// 清理空的 type 数组
    cart_data.value = cart_data.value.filter(item => item.type.length > 0);
    totalPriceList.value = totalPriceList.value.filter(item => item.type.length > 0);
  } catch (error) {
    console.error('商品删除失败', error);
    ElMessage({
      message: '商品删除失败',
      type: 'error',
    });
  }
};

// 点击支付
const handlePay = async (arr) => {

  try {
    if (TotalPrice === 0) {
      ElMessage({
        message: '请选择商品',
        type: 'error',
      });
      return;
    }
    let cart = []
    await arr.forEach(item => {
      item.type.forEach(typeItem => {
        cart.push(typeItem.cart_id)
      })
    })

    if (totalPriceList.value.length === 0) {
      ElMessage({
        message: '请选择商品',
        type: 'error',
      });
      return;
    }

    const formData = new FormData()
    formData.append("cart_ids", cart)
    const response = await HTTP.post('/cart_to_order', formData);

    if (response.code === 10200) {
      ElMessage({
        message: '支付成功，已加入订单',
        type: 'success',
      });
      await handleDeleteAll();
    } else {
      ElMessage({
        message: '支付失败',
        type: 'error',
      });
    }
  } catch (e) {
    console.error(e);
    ElMessage({
      message: '支付过程中发生错误，请稍后再试',
      type: 'error',
    });
  } finally {
    dialogFormVisible.value = false;
  }
};
</script>

<template>
  <div class="cart">
    <h1>
      <i class="iconfont icon-fanhui4"
         @click="handleBack"
      ></i>
    </h1>
    <div class="cart_main">
      <div class="el-card">
        <el-table
            :data="cart_data"
            style="width: 100%"
            :header-cell-style="{backgroundColor: '#ffdada'}"
            :cell-style="{backgroundColor: '#ffdada'}"
            :row-style="{backgroundColor: '#ffdada'}"
            empty-text="购物车空空如也~">
          <el-table-column type="expand">
            <template #default="props">
              <div class="magin_auto">
                <p v-for="(item,index) in props.row.type" :key="index">
                  商品配置：{{ item.type_name }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="图片" prop="img" width="150px">
            <template v-slot:default="scope">
              <el-image :src="scope.row.img" style="width:90px;height:120px;"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品名称" prop="name" width="200px"/>
          <el-table-column label="价格" prop="price">
            <template #default="scope">
              <span style="color: red">￥{{ scope.row.price + '元' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="150px">
            <template v-slot="scope">
              <div class="form-check form-switch">
                <input class="form-check-input" style="width: 60px;margin-left:5px;height: 30px;cursor: pointer"
                       type="checkbox"
                       v-model="totalPriceList"
                       @change="handleCheckOut" :value="scope.row" role="switch" id="flexSwitchCheckDefault">
              </div>
            </template>
          </el-table-column>
          <el-table-column align="right" label="操作">
            <template #default="scope">
              <el-popconfirm
                  width="220"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon-color="#626AEF"
                  @confirm="handleDelete(scope.row.type[0].cart_id)"
                  title="你确定删除这件商品吗？"
              >
                <template #reference>
                  <el-button
                      size="small"
                      type="danger"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
      </div>

      <div class="cart_right">

        <div class="cart_cat">
          <div class="flex flex-col items-center justify-center">
            <img src="@/assets/icon/cat.png" class="cat" alt="猫猫购物车~" @click="catMove">
            <h3>猫猫购物车~</h3></div>
        </div>

        <div class="cart_bottom">
          <div class="cart_container">
            <div>
              <div class="form-check form-switch">
                <input class="form-check-input" style="width: 60px;margin-left:5px;height: 30px;cursor: pointer"
                       type="checkbox"
                       v-model="AllChecked"
                       @change="handleCheckAll" role="switch" id="flexSwitchCheckDefault">
                <label class="form-check-label"
                       style="width: 60px;height: 30px;line-height: 30px;font-size:20px;margin: 5px 0 0 10px;font-weight: bold"
                       for="flexSwitchCheckDefault">全选</label>
              </div>
            </div>

            <div>
              <el-popconfirm
                  width="220"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon-color="#626AEF"
                  @confirm="handleDeleteAll"
                  title="你确定删除选中的这些吗？"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>

            <div class="flex_cart">
              <p class="text-red-500">￥{{ TotalPrice.toFixed(2) }}</p>
              <p>元</p>
            </div>
            <div>
              <el-dialog v-model="dialogFormVisible" title="请支付" width="500">
                <p>总价{{ TotalPrice.toFixed(2)  }}元</p>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">返回</el-button>
                    <el-button type="primary" @click="handlePay(totalPriceList)">
                      支付
                    </el-button>
                  </div>
                </template>
              </el-dialog>
              <el-button type="warning" @click="dialogFormVisible = true">结算</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">

.magin_auto {
  height: 40px;
  display: flex;
  flex-direction: column;

  p {
    margin-left: 30px;
  }
}

.el-button {
  font-weight: bold;
  font-family: "宋体", serif;
  color: black;
  border: 2px black solid;
}

.elips {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cart {
  width: 1535px;
  height: 100vh;
  margin: 0 auto;
  overflow: hidden;

  h1 {
    i {
      cursor: pointer;
      font-size: 40px;
      font-weight: bold;
    }
  }

  .cart_main {
    width: 1535px;
    height: 100vh;
    display: flex;

    .el-card {
      margin-left: 30px;
      width: 800px;
      height: 90%;
      background-color: #ffdada;
      border: none;
      border-radius: 10px;
      overflow-y: scroll;
    }

    .cart_right {
      width: 700px;
      height: 90%;

      .cart_cat {
        width: 100%;
        height: 80%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .cart_bottom {
        margin-left: 20px;
        width: 100%;
        height: 20%;

        .cart_container {
          margin-top: 80px;
          width: 100%;
          height: auto;
          display: flex;
          justify-items: center;
          justify-content: space-evenly;

          .el-button {
            font-size: 20px;
            border-radius: 10px;
            width: 110px;
            height: 40px;
          }

          .flex_cart {
            display: flex;
            width: 200px;
            height: 40px;
            font-size: 20px;
            overflow-x: scroll;
            overflow-y: hidden;
            font-weight: bold;
            font-family: "宋体", serif;

            p {
              line-height: 40px;
            }
          }
        }
      }
    }
  }
}
</style>